package com.example.kfcclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class OrderFood extends Activity {

	int number_table;
	
	JSONObject jsonProduct;
	JSONObject json = new JSONObject() ;
	
	JSONArray jArray = new JSONArray();
	
	ArrayAdapter<OrderItem> adapter;
	
	String[] Array_spinner;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// khởi tạo các arraylist 
		ArrayList<String> name = new ArrayList<String>();
		ArrayList<String> number = new ArrayList<String>();
		ArrayList<Integer> price = new ArrayList<Integer>();
		////////////////////////////////////////////////////
		
		setContentView(R.layout.oder_food);
		
		//lấy dữ liệu bunlde từ activity ListFood gửi sang
		Bundle b = getIntent().getExtras();
		name = b.getStringArrayList("name");
		number = b.getStringArrayList("number");
		price = b.getIntegerArrayList("price");
		number_table = b.getInt("table");
		/////////////////////////////////////////////////
		
		int total = 0;
		
		final ArrayList<OrderItem> list = new ArrayList<OrderItem>();
		for(int i=0;i<name.size();i++)
		{
			// lưu các giá trị lấy từ bundle vào class OrderItem
			OrderItem item = new OrderItem();
			item.setName(name.get(i).toString());
			item.setNumber(number.get(i).toString());
			item.setPrice(price.get(i));
			list.add(item);
			/////////////////////////////////////////////////
		}
			
		// set adapter cho listview
		final ListView lv = (ListView) findViewById(R.id.list_order);
		adapter = new OrderListAdapter(this, list);
		lv.setAdapter(adapter);
		///////////////////////////////////////////////////////
		
		// set sự kiện click cho listview
		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> a, View v,  int position,
					long id) {
				// TODO Auto-generated method stub
				AlertDialog.Builder adb = new AlertDialog.Builder(OrderFood.this);
				adb.setTitle("Delete ?");
				adb.setMessage("Do you want delete ' " + ((OrderListAdapter) adapter).getItemName(position) + "'?");
				final int positionToRemove = position;
				adb.setNegativeButton("Cancel", null);
				adb.setPositiveButton("OK", new AlertDialog.OnClickListener() {
					
					// set sự kiện click cho builder Dialog, khi click vào sẽ xóa 1 dòng listview
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						int new_total = 0;
						list.remove(positionToRemove);
						adapter.notifyDataSetChanged();
						
						// update lại tổng giá tiền
						int size = adapter.getCount();
						for(int i=0;i<size;i++)
						{
							new_total += ((OrderListAdapter) adapter).getItemPrice(i) * Integer.parseInt(((OrderListAdapter) adapter).getItemNumber(i));
								
						}	
						TextView tvTotal = (TextView) findViewById(R.id.total);
						tvTotal.setText(new_total+" vnđ");
						///////////////////////////////
					}
				});
				adb.show();
			}
		});
		
		
		// tính toán tổng giá tiền 
		int size = adapter.getCount();
		for(int i=0;i<size;i++)
		{
			total += ((OrderListAdapter) adapter).getItemPrice(i) * Integer.parseInt(((OrderListAdapter) adapter).getItemNumber(i));
		}	
	
		TextView tvTotal = (TextView) findViewById(R.id.total);
		tvTotal.setText(total+" vnđ");
		/////////////////////////////////////////////////
		
		// khởi tạo comboBox
		Array_spinner = new String[number_table];
		for(int i=1;i<=number_table;i++)
		{
			Array_spinner[i-1] = "Bàn Số " + i; 
		}
		Spinner spinner = (Spinner) findViewById(R.id.combobox);
		ArrayAdapter<String> adapter_spinner = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,Array_spinner);
		spinner.setAdapter(adapter_spinner);
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				Log.i("so ban", Array_spinner[arg2]);
				OrderItem.setNumberTable(arg2+1);
				Log.i("number Table",OrderItem.getNumberTable()+"");
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		// set button capnhat, khi click vào sẽ cập nhật tổng giá tiền khi thay đổi số lượng sản phẩm
		Button capnhat = (Button) findViewById(R.id.cap_nhat);
		capnhat.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int new_total = 0;
				adapter.notifyDataSetChanged();
				int size = adapter.getCount();
				
					for(int i=0;i<size;i++)
					{
						new_total += ((OrderListAdapter) adapter).getItemPrice(i) * Integer.parseInt(((OrderListAdapter) adapter).getItemNumber(i));
					}
				TextView tvTotal = (TextView) findViewById(R.id.total);
				tvTotal.setText(new_total+" vnđ");
			}
		});
		
		// set button thwm, khi click vào sẽ gọi lại activity ListFood để thêm sản phẩm
		Button them = (Button) findViewById(R.id.them);
		them.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent resultIntent = new Intent();
				int size = adapter.getCount();
				Bundle bundle = new Bundle();
				ArrayList<String> result_number = new ArrayList<String>();
				ArrayList<String> result_name = new ArrayList<String>();
				for(int i=0;i<size;i++)
				{
					result_number.add(((OrderListAdapter) adapter).getItemNumber(i));
					result_name.add(((OrderListAdapter) adapter).getItemName(i));
				}
				bundle.putStringArrayList("result_number", result_number);
				bundle.putStringArrayList("result_name", result_name);
				resultIntent.putExtras(bundle);
				setResult(RESULT_OK,resultIntent);
				finish();
			}
		});
		
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.send_server, menu);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId())
		{
			case R.id.send_server:
			{
				
				//adapter.notifyDataSetChanged();
				int size = adapter.getCount();
				Log.i("size 2", size+"");
				try
				{
					if(!json.has("product"))
					{
						for(int i=0;i<size;i++)
						{
							jsonProduct = new JSONObject();
							jsonProduct.put("name", ((OrderListAdapter) adapter).getItemName(i));
							jsonProduct.put("number", ((OrderListAdapter) adapter).getItemNumber(i));
							jArray.put(i,jsonProduct);
						}
						json.put("product", jArray);
						json.put("table",OrderItem.getNumberTable());
						Log.i("json object 1", json.toString());
					}
					else
					{
						json.remove("product");
						json.remove("table");
						for (int i = 0, len = jArray.length(); i < len; i++) {
						    JSONObject obj = jArray.getJSONObject(i);
						    // Do your removals
						    obj.remove("name");
						    obj.remove("number");
						    // etc.
						}
							Log.i("json fsafsafa", json.toString());
							for(int i=0;i<size;i++)
							{
								jsonProduct = new JSONObject();
								jsonProduct.put("name", ((OrderListAdapter) adapter).getItemName(i));
								jsonProduct.put("number", ((OrderListAdapter) adapter).getItemNumber(i));
								jArray.put(i,jsonProduct);
							}
							json.put("product", jArray);
							json.put("table",OrderItem.getNumberTable());
							Log.i("json object 2", json.toString());
					}
				}
				catch (JSONException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
				new sendJson().execute();
				return false;
			}
			default:return super.onOptionsItemSelected(item);
		}
		
	}
	
	public class sendJson extends AsyncTask<Void, Void, Void>
	{

		private ProgressDialog progressDialog;
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			this.progressDialog = ProgressDialog.show(OrderFood.this, "", "loading...");
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try{
				String url = "http://khoaluankfc.freevnn.com/server.php";
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPostRequest = new HttpPost(url);
				
				
				//httpPostRequest.setHeader("json",json.toString());
				StringEntity se;
				se = new StringEntity(json.toString(),"UTF-8");
				se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
				httpPostRequest.setEntity(se);
				
				long t = System.currentTimeMillis();
				HttpResponse response = (HttpResponse) httpClient.execute(httpPostRequest);
				Log.i("http client", "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
				
				HttpEntity entity = response.getEntity();
				if(entity!=null)
				{
					 InputStream in = response.getEntity().getContent(); // Get the
                     // data in
                         // the
                         // entity
					 String a = convertStreamToString(in);
					 Log.i("Read from Server", a);
				}
				
			}
			catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return null;
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			progressDialog.dismiss();
			Toast.makeText(OrderFood.this, "gửi thành công", Toast.LENGTH_LONG).show();
			Intent intent = new Intent(OrderFood.this,ListFood.class);
			startActivity(intent);
		}
		
	}
	private static String convertStreamToString(InputStream is) {

	    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();

	    String line = null;
	    try {
	        while ((line = reader.readLine()) != null) {
	            sb.append(line + "\n");
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        try {
	            is.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	    return sb.toString();
	}
}
